﻿using System;
using System.Text;
using System.Threading;
using Core.Common.Monitor;
using Core.Function;
using Newtonsoft.Json.Linq;
using Tool.Web.HttpHelper;
using static Core.Common.Global;

namespace Core.Monitors
{
	public class BiliLive : Tool.Common.Monitor
	{
		int num = 0;
		bool isFirst = true;

		public BiliLive(object flag) : base(flag) 
		{
			ClearAllCloseEvent();
			ClearAllStartEvent();
			CloseEvent += () => CQ.Log($"关闭了对{flag}的B站直播监控任务");
			StartEvent += () => CQ.Log($"开启了对{flag}的B站直播监控任务");
		}

		protected override void Handle()
		{
			JObject jObject;
			int num2;
			try
			{
				jObject = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get("https://api.live.bilibili.com/room/v1/Room/getRoomInfoOld?mid=" + flag)));
				num2 = jObject["data"]["liveStatus"].ToObject<int>();
				if (isFirst)
				{
					num = num2;
					isFirst = false;
					return;
				}
			}
			catch (Exception ex)
			{
				CQ.Log($"本次uid为{flag}的直播无数据,错误信息为:{ex.Message}");
				return;
			}
			if (num != num2)
			{
				MonitorInfo monitorInfo = BiliLiveInfo.Find((e) => e.flag == (string)flag);
				lock (monitorInfo)
				{
					string name =BiliBili.GetName(long.Parse((string)flag));
					foreach (MonitorItem item in monitorInfo.item)
					{
						if (item.status == 1)
						{
							string msg = "你关注的up" + name + ((num2 == 0) ? "下播了\r\n" : "开播了\r\n") + jObject["data"]["title"]?.ToString() + "\r\n" + jObject["data"]["url"]?.ToString();
							if (item.type == 0)
							{
								CQ.SendGroupMessage(item.num, msg);
							}
							if (item.type == 1)
							{
								CQ.SendPrivateMessage(item.num, msg);
							}
							Thread.Sleep(1000);
						}
					}
				}
				num = num2;
			}
		}
	}
}
